package net.aiotos.common.ice;

import com.alibaba.fastjson.JSON;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import net.aiotos.sdk.IOTOSysI;
import net.aiotos.common.dto.ErrorEnum;
import net.aiotos.common.dto.HeartbeatDTO;
import net.aiotos.common.dto.ResultDTO;

import java.util.Date;

@Slf4j
public class HeartBeatThread extends Thread
{
    public volatile boolean exit = false;

    private final IOTOSysI iotoSysI;

    private final long newTime = System.currentTimeMillis();

    private volatile boolean runIng = true;

    public HeartBeatThread(@NonNull final IOTOSysI iotoSysI)
    {
        this.setName(this.getClass().toString());
        this.iotoSysI = iotoSysI;
    }

    @SuppressWarnings("static-access")
    public void run()
    {
        log.info("心跳守护服务启动[{}]", getId());
        Date date = new Date();
        while (!exit)
        {
            try
            {
                this.sleep(iotoSysI.getHeartbeat() * 1000);
                if (runIng)
                {
                    HeartbeatDTO heartbeatDTO = iotoSysI.heartbeat();
                    date.setTime(heartbeatDTO.getServertime());
                    log.info("heartbeat runTime:{}, time:{}", (System.currentTimeMillis() - newTime) / 1000 / 60, date);
                    if (heartbeatDTO != null && heartbeatDTO.getCode() != null && heartbeatDTO.getCode() != 0)
                    {
                        runIng = false;
                        while (true)
                        {
                            // 循环尝试连接直到成功
                            String ret = "";
                            //prx.addClient(uuidSession, identity);
                            ResultDTO info = JSON.parseObject(ret, ResultDTO.class);
                            if (null != info && null != info.getCode() && info.getCode() == ErrorEnum.Successfull)
                            {
                                runIng = true;
                                break;
                            }
                        }
                    }

                }
            } catch (Ice.CommunicatorDestroyedException e) {
                log.warn("上级已经销毁，可以自杀了");
                exit = true;
            } catch (Exception e)
            {
                e.printStackTrace();
            }
        }
        log.info("heartbeat runTime:{}, time:{}", (System.currentTimeMillis() - newTime) / 1000 / 60, date);
    }
}
